package com.gaohe.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gaohe.common.R;
import com.gaohe.pojo.Classes;
import com.gaohe.pojo.User;
import com.gaohe.pojo.UserCard;
import com.gaohe.pojo.UserClasses;
import com.gaohe.service.ClassesService;
import com.gaohe.service.UserCardService;
import com.gaohe.service.UserClassesService;
import com.gaohe.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;

@Slf4j
@RestController
@RequestMapping("/userClasses")
public class UserClassController {


    @Autowired
    private UserService userService;
    @Autowired
    private ClassesService classesService;
    @Autowired
    private UserCardService userCardService;
    @Autowired
    private UserClassesService userClassesService;

    /**
     * 根据用户 id 查看 课程
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R getClassByUserId(@PathVariable Long id) {
        LambdaQueryWrapper<UserClasses> qw = new LambdaQueryWrapper<>();
        qw.eq(UserClasses::getUserId, id);
        return R.success(userClassesService.list(qw));
    }

    /*--------------------小程序端----------------*/
    @PostMapping("/chooseClasses")
    public R chooseClasses(@RequestBody Map<String, Long> map) {
        //获取 用户 课程 id
        Long userId = map.get("userId");
        Long classId = map.get("classId");
        //获取课程对象
        Classes classes = classesService.getById(classId);
        //获取用户对象
        User user = userService.getById(userId);
        //判断课程过期
        if (classes.getEndTime().isBefore(LocalDateTime.now())) {
            return R.error("课程已经过期，无法选课");
        }
        //判断课程人数
        if (classes.getPnum() >= classes.getPmax()) {
            return R.error("所选课程人数已满，无法选课");
        }
        //判断用户是否禁用
        if (user.getStatus() == 0) {
            return R.error("用户被禁用，无法选课");
        }
        //判断用户是否有此卡
        //获取卡列表
        List<UserCard> userCardsAll = userCardService.getCardsByUserId(userId);
        //1.过期卡、次卡次数、卡和课标签关联
        List<UserCard> userCardOK = userCardsAll.stream().filter(item -> {
            //过期
            return item.getEndDate().isAfter(LocalDate.now());
        }).filter(item -> {
            //次卡 次数
            boolean flag = false;
            if (item.getType().equals("期限卡")) {
                flag = true;
            }
            if (item.getType().equals("次卡")) {
                //判断次卡次数
                if (item.getCount() >= 1) {
                    flag = true;
                }
            }
            return flag;
        }).filter(item -> {
            //卡和课的标签
            String[] tagsCard = item.getTags().split(",");
            String[] tagsClass = classes.getTags().split(",");
            //取交集
            Collection<String> intersection = CollectionUtil
                    .intersection(Arrays.asList(tagsCard), Arrays.asList(tagsClass));
            if (ObjectUtil.isNotEmpty(intersection) && ObjectUtil.isNotNull(intersection)) {
                return true;
            }
            return false;
        }).map(item -> {
            //处理业务并返回对象
            item.setDisable(true);
            return item;
        }).toList();
        //是否有卡
        if (userCardOK.isEmpty()) {
            return R.error("无可用卡，请先购买卡");
        }
        //用户选择卡
        //优先使用期限卡
        UserCard tempUserCard = null;
        for (UserCard userCard : userCardOK) {
            if (userCard.getType().equals("期限卡")) {
                tempUserCard = userCard;
                break;
            }
        }
        //没有期限卡 是否有次卡
        if (tempUserCard == null) {
            for (UserCard userCard : userCardOK) {
                if (userCard.getType().equals("次卡")) {
                    userCard.setCount(userCard.getCount() - 1);
                    //同步信息
                    userCardService.updateById(userCard);
                    tempUserCard = userCard;
                    break;
                }
            }
        }
        //userClass新增
        UserClasses userClasses = new UserClasses();
        userClasses.setUserId(userId);
        userClasses.setClassId(classId);
        userClasses.setUserName(user.getName());
        userClasses.setClassName(classes.getName());
        userClasses.setStatus(1);
        userClasses.setIsDeleted(0);
        userClasses.setTags(classes.getTags());
        boolean save = userClassesService.save(userClasses);
        classes.setPnum(classes.getPnum()+1);
        classesService.updateById(classes);
        return save ? R.success("选课成功") : R.error("选课失败");
    }

    /**
     * 老师查看总课时
     *
     * @param tid
     * @return
     */
    @GetMapping("/getClassesTotalCount/{id}")
    public R getClassesTotalCount(@PathVariable("id") Long tid) {
        Long count = userClassesService.getTotalCount(tid);
        return R.success(count);
    }

    /**
     * 查看月课时
     *
     * @param tid
     * @return
     */
    @GetMapping("/getMouthTotal/{id}")
    public R getMouthTotal(@PathVariable("id") Long tid) {
        Long mouthCount = userClassesService.getMouthCount(tid);
        return R.success(mouthCount);
    }

    /**
     * 根据 课程 Id 查询用户
     *
     * @param classId
     * @return
     */
    @GetMapping("/getUserByClassId/{id}")
    public R getUserByClassId(@PathVariable("id") Long classId) {
        return R.success(userClassesService.getUserByClassId(classId));
    }

    /**
     * 修改会员状态
     *
     * @param classId
     * @param userId
     * @param status
     * @return
     */
    @PutMapping("/attendance")
    public R attendance(@RequestParam Long classId,
                        @RequestParam Long userId,
                        @RequestParam Integer status) {
        LambdaQueryWrapper<UserClasses> qw = new LambdaQueryWrapper<>();
        qw.eq(UserClasses::getUserId, userId);
        qw.eq(UserClasses::getClassId, classId);
        UserClasses userClasses = new UserClasses();
        userClasses.setStatus(status);
        return userClassesService.update(userClasses, qw) ?
                R.success("修改成功") : R.error("修改失败");
    }
}
